package leetcode_周赛._2021._202106._20210620;

/**
 * @author yzh
 * @version 1.0
 * @date 2021/6/20 11:07
 * 统计子岛屿
 * 算法：动态规划
 */
public class _5791 {
    public static void main(String[] args) {
        System.out.println(new _5791().countSubIslands(new int[][]{{1, 0, 1, 0, 1}, {1, 1, 1, 1, 1}, {0, 0, 0, 0, 0}, {1, 1, 1, 1, 1}, {1, 0, 1, 0, 1}},
                new int[][]{{0, 0, 0, 0, 0}, {1, 1, 1, 1, 1}, {0, 1, 0, 1, 0}, {0, 1, 0, 1, 0}, {1, 0, 0, 0, 1}}));
    }

    public int countSubIslands(int[][] grid1, int[][] grid2) {
        int m = grid1.length, n = grid1[0].length;
        int[][] grid3 = new int[m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                int x = grid1[i][j] & grid2[i][j];
                if (x == 0) continue;
                if (i == 0) {
                    if (j == 0) {
                        if (grid1[i + 1][j] == 0 && grid2[i + 1][j] == 1) x = 0;
                    } else {
                        if (grid1[i][j - 1] == 0 && grid2[i][j - 1] == 1 ||
                                grid1[i + 1][j] == 0 && grid2[i + 1][j] == 1) x = 0;
                    }
                } else if (i < m - 1) {
                    if (j == 0) {
                        if (grid1[i - 1][j] == 0 && grid2[i - 1][j] == 1 ||
                                grid1[i + 1][j] == 0 && grid2[i + 1][j] == 1) x = 0;
                    } else {
                        if (grid1[i - 1][j] == 0 && grid2[i - 1][j] == 1 ||
                                grid1[i][j - 1] == 0 && grid2[i][j - 1] == 1 ||
                                grid1[i + 1][j] == 0 && grid2[i + 1][j] == 1) x = 0;
                    }
                } else if (i == m - 1) {
                    if (j == 0) {
                        if (grid1[i - 1][j] == 0 && grid2[i - 1][j] == 1) x = 0;
                    } else {
                        if (grid1[i - 1][j] == 0 && grid2[i - 1][j] == 1 ||
                                grid1[i][j - 1] == 0 && grid2[i][j - 1] == 1) x = 0;
                    }
                }
                grid3[i][j] = x;
            }
        }
        int ans = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid3[i][j] != 1) continue;
                if (i == 0) {
                    if (j == 0 || grid3[i][j - 1] != 1) ++ans;
                } else {
                    if (j == 0) {
                        if (grid3[i - 1][j] != 1) ++ans;
                    } else {
                        if (grid3[i - 1][j] != 1 && grid3[i][j - 1] != 1) ++ans;
                    }
                }
            }
        }
        return ans;
    }

}
